import React, { useState, useEffect } from 'react'
import { Card, List, Tag, Button, Space, message } from 'antd'
import { BellOutlined, PlayCircleOutlined, CloudDownloadOutlined } from '@ant-design/icons'
import { apiService } from '../services/api'

interface PolicyRule {
  id: string
  description: string
  mode: string
  left: {
    metric: string
    transform: string
  }
  op: string
  right: number
  window: any
  notify: {
    throttleMinutes: number
  }
}

const PolicySummary: React.FC = () => {
  const [rules, setRules] = useState<PolicyRule[]>([])
  const [loading, setLoading] = useState(false)

  // 模拟策略配置（实际应该从API获取）
  useEffect(() => {
    const mockRules: PolicyRule[] = [
      {
        id: "cny-upper",
        description: "JPY→CNY 超过上限",
        mode: "single",
        left: { metric: "JPY_CNY", transform: "rate_or_amount1000" },
        op: ">",
        right: 0.0500,
        window: null,
        notify: { throttleMinutes: 60 }
      },
      {
        id: "cny-lower",
        description: "JPY→CNY 低于下限",
        mode: "single",
        left: { metric: "JPY_CNY", transform: "rate_or_amount1000" },
        op: "<",
        right: 0.0450,
        window: null,
        notify: { throttleMinutes: 60 }
      },
      {
        id: "cny-daily-change-up",
        description: "JPY→CNY 日涨幅超过1%",
        mode: "single",
        left: { metric: "JPY_CNY", transform: "pct_change_1d" },
        op: ">",
        right: 0.01,
        window: { lookbackDays: 1 },
        notify: { throttleMinutes: 120 }
      },
      {
        id: "cny-daily-change-down",
        description: "JPY→CNY 日跌幅超过1%",
        mode: "single",
        left: { metric: "JPY_CNY", transform: "pct_change_1d" },
        op: "<",
        right: -0.01,
        window: { lookbackDays: 1 },
        notify: { throttleMinutes: 120 }
      },
      {
        id: "usd-upper",
        description: "JPY→USD 超过上限",
        mode: "single",
        left: { metric: "JPY_USD", transform: "rate_or_amount1000" },
        op: ">",
        right: 0.0070,
        window: null,
        notify: { throttleMinutes: 60 }
      },
      {
        id: "usd-lower",
        description: "JPY→USD 低于下限",
        mode: "single",
        left: { metric: "JPY_USD", transform: "rate_or_amount1000" },
        op: "<",
        right: 0.0060,
        window: null,
        notify: { throttleMinutes: 60 }
      }
    ]
    setRules(mockRules)
  }, [])

  const handleTriggerEvaluation = async () => {
    try {
      setLoading(true)
      await apiService.triggerEvaluation()
      message.success('策略评估已触发')
    } catch (error) {
      message.error('触发策略评估失败')
    } finally {
      setLoading(false)
    }
  }

  const handleTriggerFetch = async () => {
    try {
      setLoading(true)
      await apiService.triggerFetch()
      message.success('数据拉取已触发')
    } catch (error) {
      message.error('触发数据拉取失败')
    } finally {
      setLoading(false)
    }
  }

  const getConditionText = (rule: PolicyRule) => {
    const { left, op, right } = rule
    let leftText = ''
    
    if (left.metric === 'JPY_CNY') {
      leftText = 'JPY→CNY'
    } else if (left.metric === 'JPY_USD') {
      leftText = 'JPY→USD'
    }
    
    if (left.transform === 'rate_or_amount1000') {
      leftText += '(1000JPY折算)'
    } else if (left.transform === 'pct_change_1d') {
      leftText += '(日涨跌幅)'
    }
    
    let opText = ''
    switch (op) {
      case '>': opText = '大于'; break
      case '<': opText = '小于'; break
      case '>=': opText = '大于等于'; break
      case '<=': opText = '小于等于'; break
      default: opText = op
    }
    
    return `${leftText} ${opText} ${right}`
  }

  const getThrottleText = (minutes: number) => {
    if (minutes < 60) {
      return `${minutes}分钟`
    } else {
      const hours = Math.floor(minutes / 60)
      const remainingMinutes = minutes % 60
      return remainingMinutes > 0 ? `${hours}小时${remainingMinutes}分钟` : `${hours}小时`
    }
  }

  return (
    <Card 
      title={
        <Space>
          <BellOutlined />
          策略配置
        </Space>
      }
      extra={
        <Space>
          <Button 
            icon={<PlayCircleOutlined />}
            onClick={handleTriggerEvaluation}
            loading={loading}
            size="small"
          >
            评估
          </Button>
          <Button 
            icon={<CloudDownloadOutlined />}
            onClick={handleTriggerFetch}
            loading={loading}
            size="small"
          >
            拉取
          </Button>
        </Space>
      }
      className="policy-summary"
    >
      <List
        dataSource={rules}
        renderItem={(rule) => (
          <List.Item className="policy-item">
            <List.Item.Meta
              title={
                <div className="policy-description">
                  {rule.description}
                </div>
              }
              description={
                <div className="policy-condition">
                  <div>条件: {getConditionText(rule)}</div>
                  <div style={{ marginTop: 4 }}>
                    <Tag size="small">节流: {getThrottleText(rule.notify.throttleMinutes)}</Tag>
                    <Tag size="small" color="blue">ID: {rule.id}</Tag>
                  </div>
                </div>
              }
            />
          </List.Item>
        )}
      />
      
      <div style={{ marginTop: 16, padding: 12, background: '#f0f2f5', borderRadius: 6 }}>
        <div style={{ fontSize: 12, color: '#666' }}>
          <div>• 系统每30分钟自动拉取最新汇率数据</div>
          <div>• 每次拉取后自动执行策略评估</div>
          <div>• 触发条件时发送钉钉通知</div>
          <div>• 每周日8:00自动清理30天前的历史数据</div>
        </div>
      </div>
    </Card>
  )
}

export default PolicySummary
